/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projetlif13.model.puissance4;

import java.util.logging.Level;
import java.util.logging.Logger;
import projetlif13.model.Board;
import projetlif13.model.IAPlayer;
import projetlif13.model.Move;
import projetlif13.scene.GameScene;
import projetlif13.tools.Utility;

/**
 *
 * @author theo
 */
public class IAPlayerP4 extends IAPlayer {

    private P4Move lastMove;
    private Board lastBoard;
    private boolean hasRequestedMove;

    public IAPlayerP4() {
        super();
    }

    @Override
    public Move getMove(Board _board) {

        lastMove = null;
        lastBoard = _board;
        hasRequestedMove = true;
        while (lastMove == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(IAPlayerP4.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        GameScene.uiclick.play();
        return lastMove;
    }

    @Override
    public void run() {
        while (true) {
            while (!hasRequestedMove) {
                if (stop) {
                    break;
                }
                try {
                    Thread.sleep(450);
                } catch (InterruptedException ex) {
                    Logger.getLogger(IAPlayerP4.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //+difficile + joue rapidement
            long timeout = 150 + (long) ((750 * Math.random())) - (difficulty * 150);
            if (timeout > 0) {
                try {
                    Thread.sleep(timeout); //plus c'ets difficile et plus il joue rapidement
                } catch (InterruptedException ex) {
                    Logger.getLogger(IAPlayerP4.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (stop) {
                break;
            }

            if (hasRequestedMove) {
                while (lastMove == null) {
                    int x = Utility.getRandomInt(0, lastBoard.getWidth());
                    if (lastBoard.getState()[x][0][0] == -1) {
                        lastMove = new P4Move(x, 0);
                    }
                }
                hasRequestedMove = false;
            }
        }


    }
}
